// lib/ui/member/member_page_card_list.dart
import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/get_user_info_entity.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/ui/member/provider/member_provider.dart';
import 'package:flutter_deer/util/input_formatter/mny_format.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';

class MemberCardListPage extends StatefulWidget {
  final Function(MemberCardData?)? onCardSelected;

  const MemberCardListPage({super.key, this.onCardSelected});

  @override
  _MemberCardListPageState createState() => _MemberCardListPageState();
}

class _MemberCardListPageState extends State<MemberCardListPage> {
  final mProvider = Get.find<MemberProvider>();

  @override
  void initState() {
    super.initState();
    // 使用 WidgetsBinding.instance.addPostFrameCallback 延迟执行网络请求
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadMemberData();
    });
  }

  // 将网络请求移到单独的方法中
  void _loadMemberData() {
    mProvider.requestIndividualAccountPage(
        mchMemberId: mProvider.mUser.value?.mchMemberId,
        phone: mProvider.mUser.value?.phone,
        onSuccess: (list) {
          if (mounted) {
            print('mProvider.mMemberCardList: ${list?.length}');
            setState(() {
              _cards = list
                      ?.map((e) => MemberCardData(
                            id: e.id,
                            cardNumber: e.showCardNo.bankCard,
                            balance: e.accountBalance.toYuan,
                            cardType: e.typeName,
                            cardName: e.cardName,
                            description: e.categoryName + getCardDesStore(e.enableBuyExcludeOil) + getSiteName(e.belongMchType, e.mchCode, e.mchName),
                            color: e.cardColor,
                            status: e.statusName,
                          ))
                      .toList() ??
                  [];
            });
          }
        });
  }

  String getSiteName(String belongMchType, String mchCode, String mchNames) {
    if (mchCode == GetUserInfoEntity.get()?.loginMerchantCode) {
      return '';
    }
    return '\n开卡油站: $mchNames';
  }

  // 获取是否包含非油
  String getCardDesStore(bool enableBuyExcludeOil) {
    if (enableBuyExcludeOil) {
      return ' + [非油]';
    }
    return '';
  }

  // 模拟会员卡数据
  List<MemberCardData> _cards = [
    // MemberCardData(
    //   id: '1',
    //   cardNumber: '8888 8888 8888 0001',
    //   balance: '1250.50',
    //   cardType: '个人卡',
    //   cardName: '尊享金卡',
    //   description: '享受全场8.5折优惠享受全场8.5折优惠享受全场8.5折优惠',
    //   color: Colors.amber,
    // ),
    // MemberCardData(
    //   id: '2',
    //   cardNumber: '8888 8888 8888 0002',
    //   balance: '890.00',
    //   cardType: 'VIP银卡',
    //   cardName: '优雅银卡',
    //   description: '享受全场9折优惠',
    //   color: Colors.grey,
    // ),
    // MemberCardData(
    //   id: '3',
    //   cardNumber: '8888 8888 8888 0003',
    //   balance: '2560.80',
    //   cardType: '钻石卡',
    //   cardName: '至尊钻石卡',
    //   description: '享受全场8折优惠及专属服务',
    //   color: Colors.blue,
    // ),
    // MemberCardData(
    //   id: '4',
    //   cardNumber: '8888 8888 8888 0004',
    //   balance: '320.00',
    //   cardType: '普通卡',
    //   cardName: '标准会员卡',
    //   description: '享受积分累积',
    //   color: Colors.green,
    // ),
    // MemberCardData(
    //   id: '5',
    //   cardNumber: '8888 8888 8888 0005',
    //   balance: '5600.00',
    //   cardType: '黑金卡',
    //   cardName: '尊贵黑金卡',
    //   description: '享受全场7.5折优惠及免费服务',
    //   color: Colors.black,
    // ),
    // MemberCardData(
    //   id: '6',
    //   cardNumber: '8888 8888 8888 0006',
    //   balance: '180.50',
    //   cardType: '普通卡',
    //   cardName: '基础会员卡',
    //   description: '新用户专享',
    //   color: Colors.teal,
    // ),
    // MemberCardData(
    //   id: '7',
    //   cardNumber: '8888 8888 8888 0007',
    //   balance: '3200.25',
    //   cardType: '铂金卡',
    //   cardName: '奢华铂金卡',
    //   description: '享受全场8折优惠及生日特权',
    //   color: Colors.purple,
    // ),
    // MemberCardData(
    //   id: '8',
    //   cardNumber: '8888 8888 8888 0008',
    //   balance: '950.75',
    //   cardType: 'VIP银卡',
    //   cardName: '经典银卡',
    //   description: '享受全场9折优惠',
    //   color: Colors.blueGrey,
    // ),
    // MemberCardData(
    //   id: '9',
    //   cardNumber: '8888 8888 8888 0009',
    //   balance: '4200.00',
    //   cardType: '钻石卡',
    //   cardName: '永恒钻石卡',
    //   description: '享受全场7.8折优惠及专属礼遇',
    //   color: Colors.cyan,
    // ),
    // MemberCardData(
    //   id: '10',
    //   cardNumber: '8888 8888 8888 0010',
    //   balance: '680.30',
    //   cardType: '金卡',
    //   cardName: '荣耀金卡',
    //   description: '享受全场8.8折优惠',
    //   color: Colors.deepOrange,
    // ),
  ];

  String? _selectedCardId;

  void _toggleCardSelection(String cardId) {
    setState(() {
      if (_selectedCardId == cardId) {
        // 重复点击取消选择
        _selectedCardId = null;
      } else {
        // 选择新卡片
        _selectedCardId = cardId;
      }

      // 回调选中的卡片
      if (_selectedCardId != null) {
        final selectedCard = _cards.firstWhere((card) => card.id == _selectedCardId);
        widget.onCardSelected?.call(selectedCard);
      } else {
        widget.onCardSelected?.call(null);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Align(
        alignment: Alignment.topLeft,
        child: Container(
          width: 400,
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '选择会员卡',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colours.text,
                ),
              ),
              const SizedBox(height: 10),
              Expanded(
                child: ListView.builder(
                  itemCount: _cards.length,
                  itemBuilder: (context, index) {
                    return _buildCardItem(_cards[index]);
                  },
                ),
              ),
            ],
          ),
        ));
  }

  Widget _buildCardItem(MemberCardData card) {
    final bool isSelected = _selectedCardId == card.id;

    return Container(
      height: 160,
      margin: const EdgeInsets.only(bottom: 12),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16),
        gradient: LinearGradient(
          colors: [
            card.color.withOpacity(0.8),
            card.color.withOpacity(0.6),
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        boxShadow: [
          BoxShadow(
            color: card.color.withOpacity(0.3),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: InkWell(
        onTap: () => _toggleCardSelection(card.id),
        borderRadius: BorderRadius.circular(16),
        child: Stack(
          children: [
            // 背景装饰图案
            Positioned(
              right: -20,
              top: -20,
              child: Opacity(
                opacity: 0.1,
                child: Icon(
                  Icons.credit_card,
                  size: 120,
                  color: Colors.white,
                ),
              ),
            ),

            // 卡片内容
            Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  // 顶部信息
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // 卡类型标签
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.3),
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: Text(
                          card.cardType,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),

                      // 选中标识
                      if (isSelected)
                        Container(
                          padding: const EdgeInsets.all(4),
                          decoration: const BoxDecoration(
                            color: Colors.white,
                            shape: BoxShape.circle,
                          ),
                          child: const Icon(
                            Icons.check,
                            color: Colors.green,
                            size: 16,
                          ),
                        ),
                    ],
                  ),

                  // 卡号
                  Text(
                    card.cardNumber,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      letterSpacing: 1.2,
                    ),
                  ),

                  // 卡名称

                  Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                    Text(
                      card.cardName,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),

                    // Text(
                    //   card.status,
                    //   style: const TextStyle(
                    //     color: Colors.white,
                    //     fontSize: 18,
                    //     fontWeight: FontWeight.bold,
                    //   ),
                    // ),

                    if (card.status.isNotEmpty)
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                        decoration: BoxDecoration(
                          color: Colors.redAccent,
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          card.status,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                  ]),

                  // 底部信息
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    // crossAxisAlignment: CrossAxisAlignment.baseline,
                    children: [
                      // 描述
                      Flexible(
                        child: Text(
                          card.description,
                          style: const TextStyle(
                            color: Colors.white70,
                            fontSize: 14,
                          ),
                          textAlign: TextAlign.start,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),

                      // 余额
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // const Text(
                          //   '余额',
                          //   style: TextStyle(
                          //     color: Colors.white70,
                          //     fontSize: 12,
                          //   ),
                          // ),
                          Text(
                            '¥ ${card.balance}',
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 会员卡数据模型
class MemberCardData {
  final String id;
  final String cardNumber;
  final String balance;
  final String cardType;
  final String cardName;
  final String description;
  final Color color;

  //状态
  final String status;

  MemberCardData({
    required this.id,
    required this.cardNumber,
    required this.balance,
    required this.cardType,
    required this.cardName,
    required this.description,
    required this.color,
    required this.status,
  });
}
